package com.meichis.mcsappframework.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;

import com.meichis.mcsappframework.R;

public class EditTextDialog extends Dialog {
    private EditText editText;
    private int inputType;
    private String text, hint = "";
    private EditTextDialogDismiss dialogDismiss;

    public interface EditTextDialogDismiss {
        void miss(String text);
    }

    public EditTextDialog(Context context, int inputType, String text, EditTextDialogDismiss dialogDismiss) {
        this(context, inputType, text, dialogDismiss, "");
    }

    public EditTextDialog(Context context, int inputType, String text, EditTextDialogDismiss dialogDismiss, String hint) {
        super(context, R.style.EditTextDialog);
        this.inputType = inputType;
        this.text = text;
        this.dialogDismiss = dialogDismiss;
        this.hint = hint;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_edittext);
        editText = (EditText) findViewById(R.id.et_dialog);
        editText.setInputType(inputType | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        editText.setText(text);
        editText.setHint(hint);
        editText.setSelection(editText.getText().length());
        editText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                switch (event.getAction()) {
                    case KeyEvent.ACTION_UP:
                        switch (keyCode) {
                            case KeyEvent.KEYCODE_BACK:
                            case KeyEvent.KEYCODE_ENTER:
                                miss();
                                break;
                        }

                }
                return false;
            }
        });

        findViewById(R.id.bt_save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                miss();
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                int[] location = new int[2];
                editText.getLocationOnScreen(location);
                if (event.getY() < location[1]) {
                    miss();
                }
                break;

        }
        return super.onTouchEvent(event);
    }

    private void miss() {
        dialogDismiss.miss(editText.getText().toString());
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        EditTextDialog.this.dismiss();
    }

}
